package com.harboursoftware.xstorage.db.sql;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.RowProcessor;

import com.harboursoftware.xstorage.ac.CanonicalUserGrantee;
import com.harboursoftware.xstorage.ac.Grant;
import com.harboursoftware.xstorage.ac.Grantee;
import com.harboursoftware.xstorage.ac.GroupGrantee;
import com.harboursoftware.xstorage.ac.Permission;

/**
 * Grant implementation of the <code>RowProcessor</code> interface.
 * 
 * <p>
 * This class is thread-safe.
 * </p>
 * 
 * @since 0.1
 * @author Simon Leung
 * @see RowProcessor
 */
class GrantRowProcessor extends BaseRowProcessor {
    @SuppressWarnings("unchecked")
    @Override
    public <T> T toBean(ResultSet rs, Class<T> type) throws SQLException {
        if (!type.equals(Grant.class)) {
            throw new IllegalArgumentException("type can only be " + Grant.class.getName() + "]");
        }
        Grantee grantee = null;
        int granteeType = rs.getInt("type");
        if (granteeType == BucketSqlDao.GRANTEE_TYPE_CANONICAL_USER) {
            String id = rs.getString("grantee_id");
            String displayName = rs.getString("grantee_display_name");
            grantee = new CanonicalUserGrantee(id, displayName);
        } else if (granteeType == BucketSqlDao.GRANTEE_TYPE_ALL_USER) {
            grantee = GroupGrantee.ALL_USERS;
        } else if (granteeType == BucketSqlDao.GRANTEE_TYPE_AUTHENTICATED_USER) {
            grantee = GroupGrantee.AUTHENTICATED_USERS;
        }

        String permissionString = rs.getString("premission");
        Permission permission = Permission.fromString(permissionString);
        Grant grant = new Grant(grantee, permission);

        return (T) grant;
    }
}